<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores'
import { userUploadAvatarService } from '@/api/user'
import { ElMessage } from 'element-plus'

const userStore = useUserStore()
const uploadRef = ref(null)
const imgUrl = ref(userStore.user.user_pic)


const fileData = ref(null) // 保存原始文件

const onSelectFile = (uploadFile) => {
  const file = uploadFile.raw
  // 1. 预览用 blob URL（可以保留）
  imgUrl.value = URL.createObjectURL(file)
  // 2. 保存文件对象，用于后续转 base64
  fileData.value = file
}

const onUpdateAvatar = async () => {
  if (!fileData.value) {
    return ElMessage.warning('请先选择图片')
  }

  // ✅ 把文件转成 base64
  const reader = new FileReader()
  reader.onload = async () => {
    const base64Str = reader.result // ✅ 这才是 base64 数据

    try {
      await userUploadAvatarService(base64Str)
      await userStore.getUser()
      ElMessage({ type: 'success', message: '更换头像成功' })
    } catch (err) {
      ElMessage.error('上传失败：' + (err.response?.data?.message || err.message))
    }
  }
  reader.onerror = () => {
    ElMessage.error('文件读取失败')
  }
  reader.readAsDataURL(fileData.value) // ✅ 执行读取
}
</script>

<template>
  <page-container title="更换头像">
    <el-row>
      <el-col :span="12">
        <el-upload ref="uploadRef" class="avatar-uploader" :auto-upload="false" :show-file-list="false"
          :on-change="onSelectFile">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <img v-else src="@/assets/avatar.jpg" width="278" />
        </el-upload>
        <br />
        <el-button @click="uploadRef.$el.querySelector('input').click()" type="primary" :icon="Plus" size="large">
          选择图片
        </el-button>
        <el-button @click="onUpdateAvatar" type="success" :icon="Upload" size="large">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </page-container>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 278px;
      height: 278px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 278px;
      height: 278px;
      text-align: center;
    }
  }
}
</style>
